home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 475 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.9 KB

  1. Path: news.iag.net!news
  2. From: jatmon@iag.net (John R Buchan)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: start array at k, not 0
  5. Date: 5 Jan 1996 17:14:15 GMT
  6. Organization: Internet Access Group, Orlando, Florida
  7. Message-ID: <4cjm97$i5s@news.iag.net>
  8. References: <Pine.OSF.3.91.960104095358.22268B-100000@io.UWinnipeg.ca>
  9. NNTP-Posting-Host: pm3-orl15.iag.net
  10. X-Newsreader: WinVN 0.99.7
  11.  
  12. In article <Pine.OSF.3.91.960104095358.22268B-100000@io.UWinnipeg.ca>, 
  13. wsimpson@uwinnipeg.ca says...
  14. >
  15. >I have come up with the following 2 methods that allow one to talk about
  16. >an array that starts at element k rather than 0.  E.g. 10 element array
  17. >y[k] to y[k+10].  Both seem to work.  Is this illusory?  Is one of the
  18.  
  19. y[k+10] would be the 11th element of your 10 element array.
  20.  
  21. >2 ways better (or a way I haven't mentioned)?
  22. >
  23. >These programs set up y[5] to y[14].
  24.  
  25. >/*method 1*/
  26. >#include <stdio.h>
  27. >
  28. >int main(void)
  29. > {
  30. > int i, x[10];
  31. > int* y;
  32. > int offset=5;  /*ie 1st index at 5, y[5]-y[14] */
  33. > y=x-offset;
  34. <snip>
  35.  
  36. The c.l.c faq (Frequently Asked Question) list explains this one in Q6.17.  
  37. Basically: "pointer arithmetic is defined only as long as the pointer points 
  38. within the same allocated block of memory, or to the imaginary "terminating" 
  39. element one past it" The faq list is available for anonymous ftp from 
  40. rtfm.mit.edu /pub/usenet/comp.lang.c. 
  41.  
  42. >int main(void)
  43. > {
  44. > int i;
  45. > int* y;
  46. > int offset=5;  
  47. > int n=10;       
  48. > y=malloc(n*sizeof(int));
  49. >
  50. > printf("offset=%d\n",offset);
  51. >
  52. > for (i=offset;i<n+offset;i++)
  53. >        {
  54. >        y[i]=i;
  55.  
  56. You allocated an array of 10 ints.  The array starts at y[0] and ends at y[9].
  57. This loop is attempting to access y[5] through y[14]. So, 6 of your accesses
  58. are illegal (y[10] through y[14]).
  59.  
  60. --
  61. John R Buchan           -:|:-     Looking for that elusive FAQ?  ftp to:
  62. jatmon@mail.iag.net     -:|:-     rtfm.mit.edu /pub/usenet-by-group/....
  63.  
  64.